package com.sq.partner.manager.controller.credit;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.Config;
import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.mybatis.model.CreditPlan;
import com.sq.partner.manager.mybatis.model.CreditProduct;
import com.sq.partner.manager.mybatis.model.CreditRisk;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.FacadePrintConf;
import com.sq.partner.manager.mybatis.model.GatewayAuwProd;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.NlifeCov;
import com.sq.partner.manager.mybatis.model.NlifeProd;
import com.sq.partner.manager.mybatis.model.NlifeRisk;
import com.sq.partner.manager.mybatis.model.TradProdPlan;
import com.sq.partner.manager.mybatis.model.TradProdProp;
import com.sq.partner.manager.mybatis.model.TradeFeeCov;
import com.sq.partner.manager.service.FeeRateService;
import com.sq.partner.manager.service.TreddeFeeCovService;
import com.sq.partner.manager.service.credit.CreditPlanService;
import com.sq.partner.manager.service.credit.CreditProductService;
import com.sq.partner.manager.util.FreeMarkerUtil;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.StrUtil;

@Controller
@RequestMapping(value="/creditProduct")
public class CreditProductController {
	private static Logger logger = LogUtil.getLog(CreditProductController.class);
	@Resource
	private TreddeFeeCovService tradeFeeCovService;
	@Resource
	private FeeRateService feeRateService;
	@Resource
	private CreditProductService creditProductService;
	@Resource
	private CreditPlanService creditPlanService;
	
	@RequestMapping(value = "/list")
	public String list() throws Exception {
		return "credit/product/list";
	}
	@RequestMapping(value = "/deProdInfo")
	public @ResponseBody Page<CreditProduct> delProdInfo(String prodCode) throws Exception {
		Page<CreditProduct> page = new Page<CreditProduct>();
		if (StrUtil.isEmpty(prodCode)) {
			page.setMessage("产品代码不能为空");
			page.setResult("error");
			return page;
		}
		CreditProduct prodInfo= creditProductService.findProdInfoById(prodCode);
		if (null != prodInfo && StrUtil.isNotEmpty(prodInfo.getStatus())) {
			if ("1".equals(prodInfo.getStatus())) {
				page.setMessage("您选择的产品当前为有效状态,暂不能删除");
				page.setResult("error");
				return page;
			}
		}
		creditProductService.deleteProd(prodCode);
		page.setMessage("删除成功");
		return page;
	}
	
	
	@RequestMapping(value = "/addReq")
	public String addReq(ModelMap model,HttpServletRequest request) throws Exception {
		List<DictDto>epolicys=DictCache.getDict(Constants.DICT_EPOLICY_LIST);
		List<DictDto> prodTypeList = DictCache.getProdType("4");
		model.put("polPoolType", prodTypeList);
		model.put("epolicys", epolicys);
		return "credit/product/add";
	}
	
	@RequestMapping(value = "/saveCreditProd")
	@ResponseBody
	public Map<String,Object> saveProd(String prodName,String prodType,String prodDesc,String epolicyCode,String epolicyTitle,HttpServletRequest request) throws Exception{
		CreditProduct creditProd = new CreditProduct();
		Map<String, Object> map = new HashMap<String,Object>();
		List<DictDto> prodTypeList = DictCache.getProdType("4");
		creditProd.setProdName(prodName);
		creditProd.setProdType(prodType);
		creditProd.setProdDesc(prodDesc);
		if(epolicyCode!=null){
			creditProd.setEpolicyCode(epolicyCode);
		}
		if(epolicyTitle!=null){
			creditProd.setEpolicyTitle(epolicyTitle);
		}
		creditProd.setStatus("0");
		TradProdPlan tradProdPlan = creditProductService.saveProd(creditProd);
		map.put("tradProdPlan", tradProdPlan);
		for (DictDto dictDto : prodTypeList) {
			if(prodType.equals(dictDto.getCode())){
				map.put("codeName", dictDto.getCodeName());
			}
		}
		return map;
	}
	
	@RequestMapping(value = "/updateCreditProd")
	public @ResponseBody Page<CreditProduct> updateProd(String prodName,String prodDesc,String status,/*String isPool,String maxDelayDay,
			String minDelayDay,String maxCancelDay,String minDays,String maxDays,String pppUnit,*/String prodCode,HttpServletRequest request) throws Exception{
		Page<CreditProduct> page = new Page<CreditProduct>();
		CreditProduct creditProd = new CreditProduct();
		creditProd.setProdName(prodName);
		creditProd.setProdDesc(prodDesc);
		creditProd.setProdCode(prodCode);
		creditProd.setStatus(status);
		
		/*creditProd.setIsPool(isPool);
		creditProd.setMaxCancelDay(maxCancelDay);
		creditProd.setMaxDays(maxDays);
		creditProd.setMaxDelayDay(maxDelayDay);
		creditProd.setMinDays(minDays);
		creditProd.setMinDelayDay(minDelayDay);
		creditProd.setPppUnit(pppUnit);*/
		boolean flag = creditPlanService.queryByProdId(prodCode);
		if (!flag) {
			boolean updateProd = creditProductService.updateProd(creditProd);
			if(updateProd){
				page.setMessage("更新成功");
			}
		}else{
			if("1".equals(status)){
				boolean updateProd = creditProductService.updateProd(creditProd);
				if(updateProd){
					page.setMessage("更新成功");
				}
			}else{
				page.setMessage("您选择的产品已配置投保方案信息，不允许改为无效");
				page.setResult("error");
			}
		}
		return page;	
	}
	
	@RequestMapping(value = "/queryProdList")
	@ResponseBody
	public Page<CreditProduct> queryPlanList(HttpServletRequest request,Integer size, Integer current, String prodCode, String prodName, String status, String startDate,
			String endDate) throws Exception{
		Page<CreditProduct> page = new Page<CreditProduct>();
		page.setCurrent(current);
		page.setSize(size);
		CreditProduct creditProd = new CreditProduct();
		creditProd.setProdCode(prodCode);
		creditProd.setProdName(prodName);
		creditProd.setStatus(status);
		creditProd.setVstartDate(startDate);
		creditProd.setVendDate(endDate);
		page.setType(creditProd);
		/*是否具有导出产品权限用户*/
		boolean flag=false;
		HttpSession  session=request.getSession();
		GatewayUser  user=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		String usersConfig=Config.getProp("imple.nlife.userCodes");
		String[] codes=separete(usersConfig);
		if(codes!=null&&codes.length>0){
			flag=Arrays.asList(codes).contains(user.getUserCode());
		}
		page.setObj(flag);
		return creditProductService.queryPage(page);
	}
	
	private String[] separete(String usersConfig) {
		if(StrUtil.isEmpty(usersConfig)){
			return null;
		}
		String[] strs=usersConfig.split(",");
		return strs;
	}
	
	@RequestMapping(value = "/dowloadProd")
	public void dowloadProd(String productCode,HttpSession session,HttpServletResponse response,HttpServletRequest request) throws Exception {

		ServletOutputStream outPutStream=null;

		/**浏览器处理*/
	    final String userAgent = request.getHeader("USER-AGENT");
	    logger.info("使用的浏览器"+userAgent);
		 try{
			 String  fileName="信保产品sql.txt";
			 if(userAgent.indexOf( "MSIE")!=-1){
				 /**ie浏览器*/
				 fileName=java.net.URLEncoder.encode(fileName,"UTF-8"); 
			 }else if(userAgent.indexOf( "Mozilla")!=-1){
				 /**火狐浏览器*/
				 fileName = new String(fileName.getBytes(), "ISO8859-1");
			 }else{
				 /**其他浏览器*/
				 fileName=java.net.URLEncoder.encode(fileName,"UTF-8"); 
			 }
			 String[] product=forProds(productCode);
			 System.out.println(product);
			 Map<String, Object> map=queryCredit(product);
			 /**查询产品信息*/
			 response.setContentType("text/plain"); 
			 response.setHeader("Content-disposition","attachment; filename="+fileName);  
	         outPutStream=response.getOutputStream(); 
	         String ss=FreeMarkerUtil.process("creditProd.ftl", map);
	         outPutStream.write(ss.getBytes());  
	         outPutStream.flush();
		    }catch(IOException e){
		    	logger.info("创建文件出错",e);
		  }finally{
			  if(outPutStream!=null){
				  outPutStream.close();
			  }
		  }
	}
	
	/**产品号处理*/
	private String[] forProds(String productCode){
		if(StrUtil.isEmpty(productCode)){
			return null;
		}
		String[] strs=productCode.split(",");
		return strs;
	}
	
	/**产品导出数据处理
	 * @throws Exception **/
	private Map<String, Object> queryCredit(String[] productCode) throws Exception{
		 Map<String, Object> map=new HashMap<String, Object>();
		 map.put("prods", productCode);
		 /**查询产品*/
		 List<CreditProduct>list=creditProductService.impCreditProd(map);
		/**查询险种*/
		 List<CreditRisk> risks=creditProductService.impCreditRisk(map);
		 map.put("list",list);
		 map.put("risks", risks);
		return map;
	}
}
